﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace IpSolution
{
    class IpOperate
    {

        public static long IpToInt(string ip)
        {
            char[] separator = new char[] { '.' };
            string[] items = ip.Split(separator);
            return long.Parse(items[0]) << 24
                    | long.Parse(items[1]) << 16
                    | long.Parse(items[2]) << 8
                    | long.Parse(items[3]);
        }
        public static string IntToIp(long ipInt)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append((ipInt >> 24) & 0xFF).Append(".");
            sb.Append((ipInt >> 16) & 0xFF).Append(".");
            sb.Append((ipInt >> 8) & 0xFF).Append(".");
            sb.Append(ipInt & 0xFF);
            return sb.ToString();
        }



        public static void TestOne()
        {
            //string ip = "10.0.3.193";
            string ip = "60.205.8.179";
            long ipInt = IpToInt(ip);
            //将ip转换成数字
            Console.WriteLine(ipInt);
            //将数字转换成ip
            Console.WriteLine(IntToIp(ipInt));


            //将数字转换成 IPAddress
            //使用long ulong int 会溢出，使用uint就没问题
            uint netInt = (uint)IPAddress.HostToNetworkOrder((Int32)ipInt);
            IPAddress ipaddr = new IPAddress((long)netInt);

            //将ip字符串，转换成 IPAddress
            IPAddress ipaddr1 = IPAddress.Parse(ip);
            Console.WriteLine(ipaddr.ToString());
            Console.WriteLine(ipaddr1.ToString());


            Console.ReadKey();
        }


    }
}
